<script setup>
import { ref } from 'vue'
import jsQR from 'jsqr'

// 响应式数据
const selectedFile = ref(null)
const previewUrl = ref('')
const decodeResult = ref('')
const loading = ref(false)
const errorMsg = ref('')
const successMsg = ref('')

// 处理文件选择
const handleFileSelect = (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  processImageFile(file)
}

// 处理图片文件的通用函数
const processImageFile = (file) => {
  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    errorMsg.value = '请选择图片文件'
    return
  }
  
  selectedFile.value = file
  errorMsg.value = ''
  decodeResult.value = ''
  
  // 创建预览URL
  const reader = new FileReader()
  reader.onload = (e) => {
    previewUrl.value = e.target.result
  }
  reader.readAsDataURL(file)
}

// 处理粘贴事件
const handlePaste = (event) => {
  const items = event.clipboardData?.items
  if (!items) return
  
  for (let i = 0; i < items.length; i++) {
    const item = items[i]
    if (item.type.startsWith('image/')) {
      const file = item.getAsFile()
      if (file) {
        processImageFile(file)
        successMsg.value = '已粘贴图片，可以开始解码！'
        setTimeout(() => {
          successMsg.value = ''
        }, 2000)
      }
      break
    }
  }
}

// 拖拽相关事件
const isDragging = ref(false)

const handleDragOver = (event) => {
  event.preventDefault()
  event.dataTransfer.dropEffect = 'copy'
  isDragging.value = true
}

const handleDragLeave = (event) => {
  event.preventDefault()
  isDragging.value = false
}

const handleDrop = (event) => {
  event.preventDefault()
  isDragging.value = false
  const files = event.dataTransfer.files
  if (files.length > 0) {
    processImageFile(files[0])
    successMsg.value = '已拖拽图片，可以开始解码！'
    setTimeout(() => {
      successMsg.value = ''
    }, 2000)
  }
}

// 解码二维码
const decodeQRCode = async () => {
  if (!selectedFile.value) {
    errorMsg.value = '请先选择图片文件'
    return
  }
  
  loading.value = true
  errorMsg.value = ''
  successMsg.value = ''
  
  try {
    // 创建图片元素
    const img = new Image()
    img.onload = () => {
      // 创建canvas
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      
      canvas.width = img.width
      canvas.height = img.height
      
      // 绘制图片到canvas
      ctx.drawImage(img, 0, 0)
      
      // 获取图片数据
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height)
      
      // 使用jsQR解码
      const code = jsQR(imageData.data, imageData.width, imageData.height)
      
      if (code) {
        decodeResult.value = code.data
        successMsg.value = '二维码解码成功！'
        
        // 3秒后清除成功消息
        setTimeout(() => {
          successMsg.value = ''
        }, 3000)
      } else {
        errorMsg.value = '未能识别到二维码，请确保图片清晰且包含有效的二维码'
      }
      
      loading.value = false
    }
    
    img.onerror = () => {
      errorMsg.value = '图片加载失败，请重新选择'
      loading.value = false
    }
    
    img.src = previewUrl.value
  } catch (error) {
    console.error('解码失败:', error)
    errorMsg.value = '解码过程中发生错误: ' + (error.message || '未知错误')
    loading.value = false
  }
}

// 清除结果
const clearResult = () => {
  selectedFile.value = null
  previewUrl.value = ''
  decodeResult.value = ''
  errorMsg.value = ''
  successMsg.value = ''
  
  // 清除文件输入
  const fileInput = document.getElementById('fileInput')
  if (fileInput) {
    fileInput.value = ''
  }
}

// 复制结果到剪贴板
const copyResult = async () => {
  if (!decodeResult.value) return
  
  try {
    await navigator.clipboard.writeText(decodeResult.value)
    successMsg.value = '内容已复制到剪贴板！'
    
    setTimeout(() => {
      successMsg.value = ''
    }, 2000)
  } catch (error) {
    console.error('复制失败:', error)
    errorMsg.value = '复制失败，请手动复制'
  }
}
</script>

<template>
  <div class="qrcode-decode" @paste="handlePaste" tabindex="0">
    <div class="page-header">
      <h2>二维码解码</h2>
      <p class="page-description">上传包含二维码的图片，快速解码获取内容</p>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="errorMsg" class="error-message">
      {{ errorMsg }}
    </div>
    
    <!-- 成功提示 -->
    <div v-if="successMsg" class="success-message">
      {{ successMsg }}
    </div>
    
    <div class="decode-container">
      <!-- 文件上传区域 -->
      <div class="upload-section">
        <h3>选择或粘贴图片</h3>
        <div class="upload-area" @dragover="handleDragOver" @dragleave="handleDragLeave" @drop="handleDrop" :class="{ 'dragging': isDragging }">
          <input 
            id="fileInput"
            type="file" 
            accept="image/*" 
            @change="handleFileSelect"
            class="file-input"
          >
          <label for="fileInput" class="upload-label">
            <div class="upload-icon-container">
              <div class="upload-icon">📷</div>
              <div class="upload-icon-secondary">📋</div>
            </div>
            <div class="upload-text">
              <p class="upload-main-text">点击选择图片文件</p>
              <p class="upload-or">或</p>
              <p class="upload-paste-text">按 Ctrl+V 粘贴图片</p>
              <p class="upload-drag-text">拖拽图片到此处</p>
            </div>
            <p class="upload-hint">支持 JPG、PNG、GIF 等格式</p>
          </label>
        </div>
        
        <!-- 图片预览 -->
        <div v-if="previewUrl" class="image-preview">
          <h4>图片预览</h4>
          <img :src="previewUrl" alt="预览图片" class="preview-image">
        </div>
      </div>
      
      <!-- 操作按钮 -->
      <div v-if="selectedFile" class="action-section">
        <button 
          @click="decodeQRCode" 
          :disabled="loading"
          class="decode-btn"
        >
          {{ loading ? '解码中...' : '开始解码' }}
        </button>
        
        <button @click="clearResult" class="clear-btn">
          清除
        </button>
      </div>
      
      <!-- 解码结果 -->
      <div v-if="decodeResult" class="result-section">
        <h3>解码结果</h3>
        <div class="result-content">
          <div class="result-text">
            {{ decodeResult }}
          </div>
          <button @click="copyResult" class="copy-btn">
            📋 复制
          </button>
        </div>
        
        <!-- 结果类型判断 -->
        <div class="result-info">
          <p class="result-type">
            类型: 
            <span v-if="decodeResult.startsWith('http')" class="type-tag url">网址链接</span>
            <span v-else-if="decodeResult.startsWith('tel:')" class="type-tag phone">电话号码</span>
            <span v-else-if="decodeResult.startsWith('mailto:')" class="type-tag email">邮箱地址</span>
            <span v-else-if="decodeResult.startsWith('wifi:')" class="type-tag wifi">WiFi信息</span>
            <span v-else class="type-tag text">文本内容</span>
          </p>
          
          <!-- 快捷操作 -->
          <div class="quick-actions">
            <a v-if="decodeResult.startsWith('http')" :href="decodeResult" target="_blank" class="action-link">
              🔗 打开链接
            </a>
            <a v-else-if="decodeResult.startsWith('tel:')" :href="decodeResult" class="action-link">
              📞 拨打电话
            </a>
            <a v-else-if="decodeResult.startsWith('mailto:')" :href="decodeResult" class="action-link">
              📧 发送邮件
            </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
:root {
  --primary-color: #3b82f6;
  --primary-light: #dbeafe;
  --primary-rgb: 59, 130, 246;
  --success-color: #10b981;
  --success-light: #d1fae5;
  --danger-color: #ef4444;
  --danger-light: #fee2e2;
  --warning-color: #f59e0b;
  --warning-light: #fef3c7;
  --dark-color: #1f2937;
  --text-secondary: #6b7280;
  --text-muted: #9ca3af;
  --border-color: #e5e7eb;
  --bg-light: #f9fafb;
  --card-bg: #ffffff;
  --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
  --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
  --shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  --border-radius-sm: 0.375rem;
  --border-radius-md: 0.5rem;
  --border-radius-lg: 0.75rem;
  --spacing-xs: 0.25rem;
  --spacing-sm: 0.5rem;
  --spacing-md: 1rem;
  --spacing-lg: 1.5rem;
  --spacing-xl: 2rem;
  --spacing-xxl: 3rem;
  --gradient-primary: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.qrcode-decode {
  background: var(--card-bg);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-lg);
  padding: var(--spacing-xl);
  margin: var(--spacing-md);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.page-header {
  text-align: center;
  margin-bottom: var(--spacing-xl);
  padding-bottom: var(--spacing-lg);
  border-bottom: 2px solid var(--border-color);
  position: relative;
}

.page-header::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 50%;
  transform: translateX(-50%);
  width: 60px;
  height: 2px;
  background: var(--gradient-primary);
  border-radius: 1px;
}

h2 {
  margin: 0 0 var(--spacing-sm) 0;
  color: var(--dark-color);
  font-weight: 700;
  font-size: 1.8rem;
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-description {
  margin: 0;
  color: var(--text-secondary);
  font-size: 1rem;
}

.error-message {
  background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%);
  color: var(--danger-color);
  padding: var(--spacing-md);
  border-radius: var(--border-radius-md);
  margin-bottom: var(--spacing-lg);
  border-left: 4px solid var(--danger-color);
  box-shadow: var(--shadow-sm);
  font-weight: 500;
}

.success-message {
  background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%);
  color: #2e7d32;
  padding: var(--spacing-md);
  border-radius: var(--border-radius-md);
  margin-bottom: var(--spacing-lg);
  border-left: 4px solid #4caf50;
  box-shadow: var(--shadow-sm);
  font-weight: 500;
  animation: slideInDown 0.3s ease-out;
}

@keyframes slideInDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.decode-container {
  max-width: 800px;
  margin: 0 auto;
}

.upload-section {
  margin-bottom: var(--spacing-xl);
}

.upload-section h3 {
  margin: 0 0 var(--spacing-lg) 0;
  color: var(--dark-color);
  font-weight: 600;
  font-size: 1.2rem;
}

.upload-area {
  position: relative;
  margin-bottom: var(--spacing-lg);
  transition: all 0.3s ease;
}

.upload-area.dragging {
  transform: scale(1.02);
}

.upload-area.dragging .upload-label {
  border-color: var(--success-color);
  background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%);
  box-shadow: 0 0 20px rgba(16, 185, 129, 0.3);
}

.file-input {
  position: absolute;
  opacity: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
  z-index: 2;
}

.upload-label {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-xxl);
  border: 3px dashed var(--primary-color);
  border-radius: var(--border-radius-lg);
  background: linear-gradient(135deg, #f8faff 0%, #e3f2fd 100%);
  cursor: pointer;
  transition: all 0.4s ease;
  min-height: 280px;
  position: relative;
  overflow: hidden;
}

.upload-label::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(59, 130, 246, 0.1), transparent);
  transition: left 0.6s ease;
}

.upload-label:hover {
  border-color: #2563eb;
  background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
  transform: translateY(-4px);
  box-shadow: 0 12px 24px rgba(59, 130, 246, 0.15);
}

.upload-label:hover::before {
  left: 100%;
}

.upload-icon-container {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
  position: relative;
}

.upload-icon {
  font-size: 4rem;
  opacity: 0.8;
  transition: all 0.3s ease;
}

.upload-icon-secondary {
  font-size: 2.5rem;
  opacity: 0.6;
  position: absolute;
  right: -20px;
  top: -10px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% {
    opacity: 0.6;
    transform: scale(1);
  }
  50% {
    opacity: 0.9;
    transform: scale(1.1);
  }
}

.upload-label:hover .upload-icon {
  transform: scale(1.1);
  opacity: 1;
}

.upload-text {
  text-align: center;
  margin-bottom: var(--spacing-md);
}

.upload-main-text {
  margin: 0 0 var(--spacing-sm) 0;
  color: var(--primary-color);
  font-weight: 600;
  font-size: 1.1rem;
}

.upload-or {
  margin: var(--spacing-sm) 0;
  color: var(--text-muted);
  font-size: 0.9rem;
  font-weight: 500;
}

.upload-paste-text {
  margin: var(--spacing-xs) 0;
  color: var(--success-color);
  font-weight: 500;
  font-size: 1rem;
}

.upload-drag-text {
  margin: var(--spacing-xs) 0;
  color: var(--text-secondary);
  font-weight: 500;
  font-size: 0.95rem;
}

.upload-hint {
  font-size: 0.85rem;
  color: var(--text-muted) !important;
  margin: 0;
  padding: var(--spacing-sm) var(--spacing-md);
  background: rgba(255, 255, 255, 0.7);
  border-radius: var(--border-radius-sm);
  border: 1px solid rgba(59, 130, 246, 0.2);
}

.image-preview {
  text-align: center;
}

.image-preview h4 {
  margin: 0 0 var(--spacing-md) 0;
  color: var(--dark-color);
  font-weight: 600;
}

.preview-image {
  max-width: 100%;
  max-height: 300px;
  border-radius: var(--border-radius-md);
  box-shadow: var(--shadow-md);
  border: 1px solid var(--border-color);
}

.action-section {
  display: flex;
  gap: var(--spacing-md);
  justify-content: center;
  margin-bottom: var(--spacing-xl);
}

.decode-btn, .clear-btn {
  padding: var(--spacing-md) var(--spacing-xl);
  border: none;
  border-radius: var(--border-radius-md);
  cursor: pointer;
  font-weight: 600;
  font-size: 1rem;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.decode-btn {
  background: var(--gradient-primary);
  color: white;
  box-shadow: var(--shadow-md);
}

.decode-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.decode-btn:not(:disabled):hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg);
}

.clear-btn {
  background: var(--bg-light);
  color: var(--text-secondary);
  border: 2px solid var(--border-color);
}

.clear-btn:hover {
  background: var(--danger-light);
  color: var(--danger-color);
  border-color: var(--danger-color);
  transform: translateY(-2px);
}

.result-section {
  background: var(--bg-light);
  padding: var(--spacing-xl);
  border-radius: var(--border-radius-lg);
  border: 1px solid var(--border-color);
}

.result-section h3 {
  margin: 0 0 var(--spacing-lg) 0;
  color: var(--dark-color);
  font-weight: 600;
  font-size: 1.2rem;
}

.result-content {
  display: flex;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
}

.result-text {
  flex: 1;
  background: white;
  padding: var(--spacing-md);
  border-radius: var(--border-radius-md);
  border: 1px solid var(--border-color);
  word-break: break-all;
  line-height: 1.5;
  font-family: monospace;
  font-size: 0.9rem;
}

.copy-btn {
  padding: var(--spacing-sm) var(--spacing-md);
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: var(--border-radius-md);
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.copy-btn:hover {
  background: #2563eb;
  transform: translateY(-1px);
}

.result-info {
  border-top: 1px solid var(--border-color);
  padding-top: var(--spacing-lg);
}

.result-type {
  margin: 0 0 var(--spacing-md) 0;
  color: var(--text-secondary);
  font-weight: 500;
}

.type-tag {
  display: inline-block;
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--border-radius-sm);
  font-size: 0.8rem;
  font-weight: 600;
  text-transform: uppercase;
}

.type-tag.url {
  background: #dbeafe;
  color: #1d4ed8;
}

.type-tag.phone {
  background: #d1fae5;
  color: #047857;
}

.type-tag.email {
  background: #fef3c7;
  color: #92400e;
}

.type-tag.wifi {
  background: #e0e7ff;
  color: #3730a3;
}

.type-tag.text {
  background: #f3f4f6;
  color: #374151;
}

.quick-actions {
  display: flex;
  gap: var(--spacing-md);
}

.action-link {
  display: inline-flex;
  align-items: center;
  gap: var(--spacing-xs);
  padding: var(--spacing-sm) var(--spacing-md);
  background: var(--primary-color);
  color: white;
  text-decoration: none;
  border-radius: var(--border-radius-md);
  font-size: 0.9rem;
  font-weight: 500;
  transition: all 0.3s ease;
}

.action-link:hover {
  background: #2563eb;
  transform: translateY(-1px);
  box-shadow: var(--shadow-sm);
}

@media (max-width: 768px) {
  .qrcode-decode {
    margin: var(--spacing-sm);
    padding: var(--spacing-lg);
  }
  
  .action-section {
    flex-direction: column;
    align-items: center;
  }
  
  .decode-btn, .clear-btn {
    width: 100%;
    max-width: 200px;
  }
  
  .result-content {
    flex-direction: column;
  }
  
  .quick-actions {
    flex-direction: column;
  }
}
</style>